/* eslint-disable */
/**
 * Created by GYL on 2018/8/24
 */
//事件模板管理
import React, { Component } from 'react';
import MyTable from "../../../components/common/MyTable";
import PublicService from "../../../services/PublicService";
import MyModal from '../../../components/common/MyModal';
import request from '../../../utils/request';
import styles from './Tab1_sub.less';
import JSGanttComponent from 'react-jsgantt'
import { Form, Input, Descriptions, Button, Timeline, Icon, Tag,  message, Popover, List, Typography, Spin } from 'antd';
import moment from 'moment';
import Gantt_Edit from './Gantt_Edit';
import Gantt_Edit_Small from './Gantt_Edit_Small';
import SubeventsInfo from './SubeventsInfo';
const { TextArea } = Input;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1315525_8t7dqol1zvn.js',
});
class Tab2_sub extends Component {

  constructor(props) {
    super(props);

    this.state = {
      taskSubeventList: [],
      approvalNumber: '',
      projectName: '',
      eventName: '',
      processHistoryList: [],
      eventAuditUserList: [],
      remark: '',
      dataSate: [],
      taskClassify: '',
      content: '',
      subeventsInfo: {},
      fileList: [],//子事件列表详情文件列表
      tabData: {},
      MyModal1Visible: false,
      ganttData: [],
      ganttList: [],
      AllfileList: []//事件文件列表
    }


    const vAdditionalHeaders = {

      planStartTime: { title: '计划开始时间' },
      planEndTime: { title: '计划结束时间' },
      workTime: { title: '计划工期' },
      actualStartTime: { title: '实际开始时间' },
      actualEndTime: { title: '实际结束时间' },
      practicalWorkTime: { title: '实际工期' },
      status: { title: '事件状态' },
      proposeTask: { title: '前置任务' },

      number: { title: '序号' },
    };
    this.editorOptions = {
      vCaptionType: 'Complete',  // Set to Show Caption : None,Caption,Resource,Duration,Complete,控制右边图形结尾显示
      vQuarterColWidth: 36,
      vDateTaskDisplayFormat: ' yyyy-mm-dd', // Shown in tool tip box
      vDayMajorDateDisplayFormat: ' yyyy-mm-dd', // Set format to display dates in the "Major" header of the "Day" view
      vWeekMinorDateDisplayFormat: 'dd 日', // Set format to display dates in the "Minor" header of the "Week" view
      vLang: 0,
      vUseSingleCell: 0,
      vShowRes: 0,
      vShowCost: 0,
      vShowComp: 0,
      vShowDur: 0,
      vShowStartDate: 0,
      vShowEndDate: 0,
      vShowPlanStartDate: 0,
      vShowPlanEndDate: 0,
      vShowTaskInfoEndDate: 1,
      vShowTaskInfoLink: parseInt(this.vShowTaskInfoLink, 10), // Show link in tool tip (0/1)
      // Show/Hide the date for the last day of the week in header for daily view (1/0)
      // vTaskInfo: 0,
      vAdditionalHeaders: vAdditionalHeaders,//左边表格头部
      vEvents: {
        taskname: this.onEvent.bind(this, this.data),//点击触发
        res: 0,
        dur: 0,
        comp: 0,
        start: 0,
        end: 0,
        planstart: 0,
        planend: 0,
        cost: 0
      },
      vEventsChange: {
        taskname: this.editValue.bind(this, this.data),//编辑触发
        res: this.editValue.bind(this, this.data),
        dur: this.editValue.bind(this, this.data),
        comp: this.editValue.bind(this, this.data),
        start: this.editValue.bind(this, this.data),
        end: this.editValue.bind(this, this.data),
        planstart: this.editValue.bind(this, this.data),
        planend: this.editValue.bind(this, this.data),
        cost: this.editValue.bind(this, this.data)
      },
      vResources: [
        { id: 0, name: 'Anybody' },
        { id: 1, name: 'Mario' },
        { id: 2, name: 'Henrique' },
        { id: 3, name: 'Pedro' }
      ],
      // vEventClickRow: console.log,
      vTooltipDelay: 1,
      vDebug: false,
      vEditable: false,//是否可以编辑
      vUseSort: 'true',
      vFormatArr: ['Day', 'Week', 'Month'],//切换控制日期选择,日,周,月
    };
  }

  componentDidMount() {
    this.getProcessTaskParticulars()
  }

  //查询审批详情
  getProcessTaskParticulars = () => {
    this.setState({
      spinning: true
    })
    request({
      url: '/pm-web/process/task/getProcessTaskParticulars',
      method: 'POST',
      data: { taskId: this.props.taskId }
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {
        this.setState({
          taskClassify: data.ret.taskClassify,
          tabData: data.ret,
          remark: data.ret.subeventsInfo.remark,
          processHistoryList: data.ret.processHistoryList,
          eventAuditUserList: data.ret.eventAuditUserList,
          approvalNumber: data.ret.approvalNumber,
          eventName: data.ret.eventName,
          projectName: data.ret.projectName,
          taskSubeventList: data.ret.taskSubeventList,
          ganttList: data.ret.ganttList,
          AllfileList: data.ret.subeventsInfo.fileList,
          spinning: false,
          SubeventsInfoData: data.ret.subeventsInfo
        })
      }
    })
    // }
  }
  tongYi = (flag) => {
    if (this.props.tabData.taskClassify == 1) {
      let params = {
        content: '',
        finishType: flag,
        taskId: this.props.taskId,
        userId: PublicService.getCookie('userId')
      }
      request({
        url: '/pm-web/process/task/taskClassifyEqualOne',
        method: 'POST',
        data: params
      }).then(data => {
        // console.log(data)
        if (data.rc === 0) {
          message.success('操作成功')
        }
      })
    }
  }

  onTextArea = (value, v) => {
    // console.log(value, v)
    this.setState({
      [value]: v.target.value
    })
  }

  onqueDing = () => {
    let params = {
      content: this.state.content,
      taskId: this.props.taskId,
      userId: PublicService.getCookie('userId')
    }
    request({
      url: '/pm-web/process/task/addComments',
      method: 'POST',
      data: params
    }).then(data => {
      // console.log()
      if (data.rc === 0) {
        message.success("评论提交成功!")
        this.getProcessTaskParticulars()
      } else {
        message.warning('评论失败!')
      }
    })
  }
  onxiangqing = (val) => {
    // console.log(val)
    let params = {
      subeventsId: val.subeventsId,
      taskId: val.taskId,

    }
    request({
      url: '/pm-web/process/task/getEventParticulars',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        this.setState({
          SubeventsInfoData: data.ret.subeventsInfo,
          SubeventsInfoVisible: true
          // fileList: data.ret.subeventsInfo.fileList
        })
      }
    })
  }

  ontongyi2 = (val, bn) => {
    // console.log(val, bn)
    if (val.taskType != 1) {
      return
    }
    let params = {
      content: '',
      finishType: bn,
      id: val.id,
      subeventsId: val.subeventsId,
      taskId: val.taskId,
      userId: PublicService.getCookie('userId')

    }
    request({
      url: '/pm-web/process/task/taskClassifyEqualTwo',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        message.success("操作成功")
        this.getProcessTaskParticulars()
      } else {
        message.warning("操作失败")
      }
    })
  }

  editValue(list, task, event, cell, column) {
    // tslint:disable-next-line:triple-equals
    const found = list.find(item => item.pID == task.getOriginalID());
    if (!found) {
      return;
    } else {
      found[column] = event ? event.target.value : '';
    }
    // console.log(found);
  }
  onEvent = (list, task, event, cell, column) => {

    if (task.getParent() == 0) {
      return
    }

    if (Number(task.getParItem().getOriginalID() < 5)) {
      //大事件
      request({
        url: '/pm-web/process/task/getEventInfoCopy',
        method: 'POST',
        data: { id: task.getCaption() }
      }).then(data => {
        // console.log(data)
        if (data.rc === 0) {
          this.setState({
            EditData: data.ret.eic,
            MyModal1VisibleBig: true,
            id: task.getCaption()
          })


        }
      })
    } else {
      //小事件
      request({
        url: '/pm-web/process/task/getSubeventsInfoCopy',
        method: 'POST',
        data: { id: task.getCaption() }
      }).then(data => {

        if (data.rc === 0) {
          this.setState({
            EditDataSmall: data.ret.sic,
            MyModal1VisibleSmall: true,
            id: task.getCaption(),
            MyModal1VisibleSmall: true,

          })


        }
      })
    }




  }

  change() {
    // console.log('change:', this.editor);
    // console.log('change2:', this.editorTwo);
  }

  setLanguage(lang) {
    this.editorOptions.vLang = lang;
    this.editor.setOptions(this.editorOptions);
  }

  customLanguage() {
    this.editor.setOptions(this.editorOptions);
  }

  changeObject() {
    this.data.randomNumber = Math.random() * 100;
  }

  changeData() {
    this.data = Object.assign({}, this.data,
      { randomNumber: Math.random() * 100 });
  }

  /**
   * Example on how get the json changed from the jsgantt
   */
  getData() {
    // const changedGantt = this.editor.get();
    // console.log(changedGantt);
  }
  onGantt = () => {
    this.setState({
      MyModal1Visible: true
    })
  }
  // 取消保存
  ModalCancel = (type) => {
    let t = this;
    t.setState({
      [type]: false,
      modalBtnLoading: false
    })
  };

  onsubeventsInfo = () => {
    this.setState({
      SubeventsInfoVisible: true
    })

  }
  render() {
    let t = this
    const content = (
      <div>
        <TextArea rows={4} value={this.state.content} onChange={this.onTextArea.bind(this, 'content')} />

      </div>
    );



    const title = (

      <div style={{ textAlign: 'center' }}> <span style={{ float: 'left' }}>请输入评论内容</span> <span onClick={this.onqueDing} style={{ cursor: 'pointer' }}><IconFont type="icon-icon-test" style={{ fontSize: 16, width: 20, height: 20 }} /><span style={{ color: 'green' }}>确定</span></span></div>

    );
    return (
      <Spin tip="Loading..." spinning={this.state.spinning}>
        <div style={{ display: 'flex', flexDirection: "column", position: 'relative', boxSize: 'border-box', padding: 5, paddingTop: 0, paddingBottom: 0, height: '100%' }}>

          {
            this.state.MyModal1Visible &&
            <MyModal
              onCancel={this.ModalCancel.bind(this, 'MyModal1Visible')}
              mask={false}
              width={1200}
              visible={this.state.MyModal1Visible}
              title={'甘特图详情'}
              footerShow={false}
              destroyOnClose={true}>
              <div className={styles.gtu}>
                <JSGanttComponent data={this.state.ganttList} options={this.editorOptions} />
              </div>
            </MyModal>
          }
          {/* 大事件编辑页面 */}
          {
            this.state.MyModal1VisibleBig && <Gantt_Edit
              ModalCancel={this.ModalCancel.bind(this, 'MyModal1VisibleBig')}
              EditData={this.state.EditData}
              onModalSave={this.onModalSave}
            />
          }
          {/* 小事件编辑页面 */}
          {
            this.state.MyModal1VisibleSmall && <Gantt_Edit_Small
              ModalCancel={this.ModalCancel.bind(this, 'MyModal1VisibleSmall')}
              EditData={this.state.EditDataSmall}
              onModalSave={this.onModalSaveSmall}
            />
          }
          {/* 事件详情 */}
          {
            this.state.SubeventsInfoVisible && <SubeventsInfo
              onCancel={this.ModalCancel.bind(this, 'SubeventsInfoVisible')}
              SubeventsInfoData={this.state.SubeventsInfoData}
              visible={this.state.SubeventsInfoVisible}
            />
          }
          <div style={{ flex: 1, maxHeight: '85vh', overflow: 'auto' }}>
            <Descriptions bordered>
              <Descriptions.Item label="审批编号" span={24}>{this.state.approvalNumber || '无'}</Descriptions.Item>
              <Descriptions.Item label="审批类型" span={24}>{this.state.taskClassify == 1 ? '事件完成审批' : this.state.taskClassify == 2 ? '事件完成检验' : this.state.taskClassify == 3 ? '事件配置审批' : this.state.taskClassify == 4 ? '项目变更审批' : 'OA审批' || '无'}</Descriptions.Item>
              <Descriptions.Item label="项目名称" span={24}>{this.state.projectName || '无'}</Descriptions.Item>
              <Descriptions.Item label="事件名称" span={24}>{this.state.eventName || '无'}</Descriptions.Item>
              <Descriptions.Item label="甘特图数据" span={24}>
                {
                  this.state.ganttList.length == 0 ? '无' :

                    <Button onClick={this.onGantt}> <IconFont type="icon-gantetu" style={{ fontSize: 20 }} /> 打开甘特图</Button>

                }

              </Descriptions.Item>

              <Descriptions.Item label="事件详情" span={24}>
                {
                  this.state.taskClassify == 1 ? <Button onClick={this.onsubeventsInfo}> <IconFont type="icon-gantetu" style={{ fontSize: 20 }} /> 打开事件详情</Button>
                    : '无'
                }
              </Descriptions.Item>


              <Descriptions.Item label="子事件列表" span={24}>
                {
                  this.state.taskSubeventList.length > 0 ? <List
                    size='small'
                    dataSource={this.state.taskSubeventList}
                    renderItem={item => (
                      <List.Item>
                        <Typography.Text mark>{item.subeventsName}</Typography.Text> {item.content}
                        <div style={{ flex: 1, textAlign: 'right', cursor: 'pointer' }}>

                          <span onClick={this.onxiangqing.bind(this, item)}><IconFont type="icon-pinglun" style={{ width: 20 }} />详情 </span>

                          <span onClick={this.ontongyi2.bind(this, item, true)}>{item.taskType == 1 ? '' : item.taskType == 2 ? '已同意' : ''}<IconFont type="icon-icon-test" style={{ width: 20, display: item.taskType == 1 ? '' : 'none' }} /><span style={{ width: 20, display: item.taskType == 1 ? '' : 'none' }} >同意</span> </span>
                          <span onClick={this.ontongyi2.bind(this, item, false)}>{item.taskType == 1 ? '' : item.taskType == 2 ? '' : '已拒绝'}<IconFont type="icon-butongyi-" style={{ width: 20, display: item.taskType == 1 ? '' : 'none' }} /><span style={{ width: 20, display: item.taskType == 1 ? '' : 'none' }} >拒绝</span> </span>
                        </div>
                      </List.Item>
                    )}
                  /> : '无'
                }

              </Descriptions.Item>


              <Descriptions.Item label="审核人列表" span={24} >
                {
                  this.state.eventAuditUserList.length == 0 ? '无' :
                    this.state.eventAuditUserList.map((item, index) => {
                      return (

                        <Tag key={index} style={{ margin: 2 }} color={item.approvalStatus == 1 ? "#108ee9" : item.approvalStatus == 2 ? "#2db7f5" : item.approvalStatus == 3 ? "#87d068" : '#f50'}>{item.userName} {item.approvalStatus == 1 ? "未审批" : item.approvalStatus == 2 ? "审批中" : item.approvalStatus == 3 ? "已同意" : '已拒绝'}</Tag>
                      )
                    })
                }
              </Descriptions.Item>


              <Descriptions.Item label="历史操作" span={24}>
                {
                  this.state.eventAuditUserList.length == 0 ? '无' :
                    <Timeline style={{ margin: 5 }}>
                      {
                        this.state.processHistoryList.map((item, index) => {
                          return (
                            <Timeline.Item dot={<Icon type="clock-circle-o" style={{ fontSize: '16px' }} />} color="red" key={index}>
                              {item.assigneeName}   {item.operationTime}    {item.taskType}
                              <p>{item.content}</p>
                            </Timeline.Item>
                          )
                        })
                      }

                    </Timeline>
                }


              </Descriptions.Item>


            </Descriptions>
          </div>
          <div style={{ height: 30, width: '100%', bottom: 0, left: 0, lineHeight: '30px', display: this.state.taskClassify == 2 ? 'none' : '' }} >

            <div className={styles.bottomBox} styke={{ width: 100 }}>

              <Popover content={content} title={title} trigger="click">
                <div style={{ flex: 1, textAlign: 'center', cursor: 'pointer' }}><IconFont type="icon-pinglun" style={{ fontSize: 16, width: 20, height: 20 }} />评论</div>
              </Popover>

            </div>

          </div>

        </div >
      </Spin>
    );


  }
}
export default Form.create()(Tab2_sub);


